<?php
/**
 * 消息模块Api Service
 *
 * 消息模块Api Service的注意及说明
 * 以下use模块请不要互相伤害
 *
 * @author    xiecz <xiecz@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */
namespace App\Services\JPush;
use Request,Response,Input;
use Illuminate\Support\Facades\DB;
use Log, Session;
use App\Services\Tool\Jpush\JpushTool;
use App\Services\Tool\DataBase\SQL;
use App\Services\Tool\GeneralTool;
use App\Services\UserService\UserTool;
use App\Services\Tool\Message\MessageTool;
use App\Services\ImgServices\ImgTool;
use App\Services\Tool\DataBase\DB_MYSQL_XCZ;
class JPushService{

    public function __construct(GeneralTool $generalT,
                                UserTool $userTool,
                                MessageTool $messageTool){
        $this->userTool = $userTool;
        $this->generalTool = $generalT;
        $this->messageTool = $messageTool;
    }



    /**
        消息类别列表
        参数：
            user_id         用户编号
     */
    function pushClassList($input){
        //判断参数是足够
        if(!isset($input['user_id'])){
            return GeneralTool::createResult('','M00002');
        }

        //判断用户是否存在
        if(!$this->userTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');
        $created_at = $this->userTool->registerTime($input['user_id']);

        $class  = $this->messageTool->getPushClassList(['user_id'=>$input['user_id'],
                                                        'where'=>['state'=>1],
                                                        'created_at'=>$created_at]);

        return GeneralTool::createResult(['list'=>$class],'M00000');

    }

    /**
        显示消息列表
        参数：
            user_id         用户编号
            page            页码
            per_page        每页数据量
            class           分类编码
     */
    public function showPushList($input){
        //判断参数是否足够
        if(!isset($input['user_id'])||
            !isset($input['per_page'])||
            !isset($input['page'])||
            !is_numeric($input['page'])||
            !is_numeric($input['per_page'])||
            !isset($input['class']))
            return GeneralTool::createResult('','M00002');



        //判断用户是否存在
        if(!$this->userTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        $created_at = $this->userTool->registerTime($input['user_id']);
        //获取已删除的推送id
        $id = $this->messageTool->getDelMessageId(['user_id'=>$input['user_id'],'is_del'=>1,'class'=>$input['class']]);

        $per_page   = empty($input['per_page'])?10:$input['per_page'];
        $result = $this->messageTool->getUserAllMessage(['user_id'=>$input['user_id'],
                                                         'id'=>$id,
                                                         'per_page'=>$per_page,
                                                         'class'=>$input['class'],
                                                         'created_at'=>(isset($input['$created_at'])?$input['created_at']:0)]);


        $read = $this->messageTool->getReadMessageCount(['user_id'=>$input['user_id']]);
        $result['unread'] = ($result['total']-$read>=0)?($result['total']-$read):0;
        $result['total_page'] = $result['last_page'];


        return GeneralTool::createResult($result,'M00000');
    }

    /**
        删除消息记录
        参数：
            user_id         用户编号
            push_id         推送编号数组
     */
    function delPush($input){
        //判断参数是否足够
        if(empty($input['user_id'])||empty($input['push_id']))
            return GeneralTool::createResult('','M00002');

        //判断用户是否存在
        if(!$this->userTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        $push_id = json_decode($input['push_id'],true);
        if(!is_array($push_id)) return GeneralTool::createResult('','M06001');

        foreach($push_id as $id){
            $class = $this->messageTool->getMessageClass(['id'=>$input['id']]);
            if(!isset($class)) continue;
            $result = $this->messageTool->delMessage(['user_id'=>$input['user_id'],
                                                      'push_id'=>$id,
                                                      'class'=>$class]);
        }

        $unRead                                 = $this->unReadCount($input);
        return $unRead;
    }
    /**
     *  获取未读推送信息数量
     * 参数：
     *      user_id                 用户编号
     */
    function unReadCount($input){
        //判断参数是否足够
        if(!isset($input['user_id'])){
            return GeneralTool::createResult('','M03002');
        }
        //判断用户是否存在
        if(!$this->userTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        $created_at = $this->userTool->registerTime($input['user_id']);

        $obj                        = (object)array();
        $obj->unread                = $this->messageTool->getAllMessageCount(['user_id'=>$input['user_id'],'created_at'=>$created_at]);
        return GeneralTool::createResult($obj,'M00000');
    }


    /**
        测试
     */
    function test($input){
        $arr = json_decode($input['arr'],true);
        $message = '有惊喜！' . $input['type'] . '送给您，' . $input['day'] . '天有效，定制一款属于自己的~';
        $title = 'Mytee送您' . $input['type'] . '啦！';
        $message_in = '有惊喜！'. $input['type'] . '送给您，' . $input['day'] . '天有效，定制一款属于自己的~';
        $images = [];

        foreach($arr as $ar){
            JpushTool::push($message,0,$ar.'',['title'      => $title,
                                            'user_id'    => $ar.'',
                                            'class'      => 'system_notification',
                                            'type'       => 1,
                                            'jump_value' => '',
                                            'template_no'=> '2',
                                            'message'    => $message_in,
                                            'images'     => [$images]]);
        }
        dd($arr);
        return $input;
    }

    /**
        意见反馈
        参数：
            user_id         用户编号
            name            姓名
            system          操作系统
            model           手机型号
            phone           电话
            body            内容
            version         应用版本
            platform        平台 IOS Android
            images          图片数组json
     */
    function feedBack($input){

        if(!isset($input['body'])||trim($input['body'])=='')
            return GeneralTool::createResult('','M10001');
        else if(!empty($input['phone'])&&!preg_match("/1[34578]{1}\d{9}$/", $input['phone']))
            return GeneralTool::createResult('','M10002');
        else if(!empty($input['name'])&&preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/",$input['name'])&&GeneralTool::getcode($input['name'])=='')
            return GeneralTool::createResult('','M10003');
        else if(!empty($input['body'])&&preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/",$input['body'])&&GeneralTool::getcode($input['body'])=='')
            return GeneralTool::createResult('','M10004');
        else if(!empty($input['model'])&&preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/",$input['model'])&&GeneralTool::getcode($input['model'])=='')
            return GeneralTool::createResult('','M10005');
        else if(!empty($input['version'])&&GeneralTool::getcode($input['version'])=='')
            return GeneralTool::createResult('','M10006');
        else if(!empty($input['platform'])&&GeneralTool::getcode($input['platform'])=='')
            return GeneralTool::createResult('','M00002');


        if(GeneralTool::getcode($input['body'])=='') return ['state'=>'M00001','message'=>'反馈内容格式异常','result'=>(object)array()];
        $input['images']    = !isset($input['images']) || !json_decode($input['images'],true) ? '[]' : $input['images'];
        $input['user_id']   = empty($input['user_id'])?'':$input['user_id'];
        $user               = UserTool::getPhoneAndName($input['user_id']);
        $input['name']      = isset($user->nick_name) ? $user->nick_name : '';
        $input['phone']     = isset($user->phone) ? $user->phone : '';

        $images = json_decode($input['images'],true);

        foreach($images as $image){
            if(!ImgTool::imageUrlIsValid($image['thumbnail']) || !ImgTool::imageUrlIsValid($image['original_image']))
                return GeneralTool::createResult('', 'M05034');
        }

        SQL::insert(array('table'=>'feedback',
                          'insert'=>array('user_id'=>$input['user_id'],
                                          'name'=>isset($input['name'])?$input['name']:'',
                                          'phone'=>isset($input['phone'])?$input['phone']:'',
                                          'system'=>isset($input['system'])?$input['system']:'',
                                          'model'=>isset($input['model'])?$input['model']:'',
                                          'body'=>(empty($input['body'])?'':bin2hex($input['body'])),
                                          'version'=>isset($input['version'])?$input['version']:'',
                                          'platform' => (isset($input['platform']) ? trim($input['platform']) : ''),
                                          'images' => $input['images'],
                                          'created_at'=>time())));
        return array('state'=>'M00000','message'=>'感谢您的反馈！','result'=>(object)array());
    }

    /**
        backstage
     */

    /**
        获取推送类别列表
     */
    function getClass(){
        $class = SQL::get(['table'=>'push_class',
                           'where'=>array('state'=>1)]);
        return $class;
    }

    /**
     *  获取消息推送记录
     */
    public function getPushRecord(){
        $record                 = DB::table('push_records')
                                  ->get();
        return $record;
    }

    /**
     *  推消息
        参数：
            plat        平台
            class       类别
            reg_id      资源编号
            title       标题
            body        内容
     */
    public function pushMessage($input){
        //判断参数
        if(!isset($input['class'])||!isset($input['title'])||!isset($input['body']))
            return GeneralTool::createResult('','M00002');
        if(isset($input['class'])&&$input['class']!='system'&&!isset($input['reg_id'])){
            return GeneralTool::createResult('','M00002');
        }

        if(empty($input['title']))
            return array('state'=>'M00001','message'=>'请填写标题');

        if(empty($input['body']))
            return array('state'=>'M00001','message'=>'请填写内容');
        $user_id = 0;
        if($input['class']=='order'){
            $order  = SQL::first(['table'=>'orders',
                                  'where'=>['order_id'=>$input['reg_id']]]);
            if(!isset($order)||!isset($order->user_id)||empty($order->user_id)) return GeneralTool::createResult('','M05011');
            $user_id = $order->user_id;
        }

        $body                   = trim($input['body']);
        //按长度截取内容为标题
        $title                  = $input['title'];
        $time                   = time();
        //推送
        if(JpushTool::push($title,(empty($input['plat'])?0:$input['plat']),$user_id,array('class'=>$input['class'],
                                                                                   'reg_id'=>$input['reg_id'],
                                                                                   'title'=>$title,
                                                                                   'type'=>1,
                                                                                   'messages'=>$body,
                                                                                   'time'=>$time,
                                                                                   'user_id'=>'0'))
           &&
           JpushTool::push_phone($title,(empty($input['plat'])?0:$input['plat']),$user_id,array('class'=>$input['class'],
                                                                                         'reg_id'=>$input['reg_id'],
                                                                                         'title'=>$title,
                                                                                         'type'=>1,
                                                                                         'messages'=>$body,
                                                                                         'time'=>$time,
                                                                                         'user_id'=>'0'))){

            return GeneralTool::createResult('','M00000');
        }else{
            return GeneralTool::createResult('','M00001');
        }
    }

    /**
     *  推链接
     */
    public function pushHtml($input){
        if(empty($input['title'])){
            return GeneralTool::createResult('标题不能为空','M00001');
        }
        if(!empty($input['url'])&&!empty($input['body'])){
            return GeneralTool::createResult('链接和内容只需要填写一个','M00001');
        }

        $title                   = iconv_strlen($input['title'])>55?mb_substr($input['title'],0,55,'utf-8'):$input['title'];
        $title  .= '...';
        $push_id                 = time().''.Session::get('admin')->id;

        if(!empty($input['url'])){

            $html                = DB::table('push_htmls')
                                   ->insert(array('push_id'=>$push_id,'user_id'=>Session::get('admin')->id,'title'=>$title,'body'=>$input['url']));
            if(JPushTool::push($title,(empty($input['plat'])?0:$input['plat']),0,
                                                                    array('state'=>1,'state_str'=>'系统通知','time'=>time(),
                                                                          'type'=>0,'url'=>$input['url'],'messages'=>$input['title'],
                                                                          'user_id'=>''))){
                $record              = DB::table('push_records')
                                       ->insert(array('user_id'=>Session::get('admin')->id,
                                                      'push_id'=>$push_id,
                                                      'body'=>$input['title'],'created_at'=>time()));
                return GeneralTool::createResult('','M00000');
            }
            return GeneralTool::createResult('','M00001');
        }
        if(empty($input['body'])){
            return GeneralTool::createResult('内容不能为空','M00001');
        }
        $body                    = bin2hex($input['body']);

        $html                    = DB::table('push_htmls')
                                   ->insert(array('push_id'=>$push_id,'user_id'=>Session::get('admin')->id,'title'=>$title,'body'=>$body));
        if($html==1){
            //推送
            $url                 = 'http://'.public_path().'/api/push/pushhtmlurl?push_id='.$push_id;

            $result              = JPushTool::push($input['title'],(empty($input['plat'])?0:$input['plat']),0,
                                                                    array('state'=>1,'state_str'=>'系统通知','time'=>time(),
                                                                          'type'=>0,'url'=>$url,'messages'=>$input['title'],
                                                                          'user_id'=>''));
            //添加推送记录
            $record              = DB::table('push_records')
                                   ->insert(array('user_id'=>Session::get('admin')->id,
                                                  'push_id'=>$push_id,
                                                  'body'=>$body,'created_at'=>time()));
            //dd($result);
            return GeneralTool::createResult('','M00000');
        }
        return GeneralTool::createResult('','M00001');
    }

    /**
     * 显示推送链接页面
     */
    public function pushHtmlUrl($input){
        $push_id                 = Input::get('push_id');
        $body                    = pack('H*',
                                   DB::table('push_htmls')
                                   ->where('push_id',$push_id)
                                   ->pluck('body'));
        return $body;
    }

    /**
        获取用户消息未读数
     */
    function get_user_message_unread($input){
        $created_at = $this->userTool->registerTime($input['user_id']);
        if(!isset($created_at)) return 0;
        $count = $this->messageTool->getAllMessageCount(['user_id' => $input['user_id'], 'created_at' => $created_at]);
        return $count;
    }

    /**
     * 定时
     */

    /**
     * 添加定时任务
     * 参数：
     *      send_time       发送时间
     *      app_id          模块编号
     *      resource_id     资源编号
     *      data_json       数据
     *
     */
    static function add_timing_job(array $arr){
        if(!isset($arr['send_time']) ||
            !isset($arr['app_id']) ||
            !isset($arr['resource_id']) ||
            !isset($arr['data_json'])){
            return GeneralTool::createResult('', 'M00002');
        }
        $result = SQL::insert(['table'  => 'push_timing_jobs',
                               'insert' => ['send_time'   => $arr['send_time'],
                                            'app_id'      => $arr['app_id'],
                                            'resource_id' => $arr['resource_id'],
                                            'data_json'   => $arr['data_json'],
                                            'created_at'  => time(),
                                            'updated_at'  => time()]]);
        return GeneralTool::createResult('', ($result ? 'M00000' : 'M00001'));
    }

    /**
     * 删除定时任务
     * 参数：
     *      app_id
     *      resource_id
     */
    static function delete_timing_job(array $arr){
        if(!isset($arr['app_id']) ||
            !isset($arr['resource_id'])){
            return GeneralTool::createResult('','M00002');
        }
        $result = SQL::update(['table'  => 'push_timing_jobs',
                               'where'  => ['app_id' => $arr['app_id'],
                                            'resource_id' => $arr['resource_id']],
                               'update' => ['state' => 0,
                                            'updated_at' => time()]]);
        return GeneralTool::createResult('', ($result ? 'M00000' : 'M00001'));
    }

    /**
     * 定时消息
     */
    static function push_timing(){
        try{
            $time = time();
            Log::info('----------进入定时推送------------');
            $db = new DB_MYSQL_XCZ('push_timing_jobs');
            $db->where(['send_state' => 0,
                        'state'      => 1]);
            $db->whereThen(['send_time', '<=', $time]);
            $result  = $db->get();
            $success = 0;
            foreach($result as $re){
                if(!isset($re->data_json)) continue;
                $arr = json_decode($re->data_json,true);
                if(!$arr ||
                    !isset($arr['notice_title']) ||
                    !isset($arr['platform']) ||
                    !isset($arr['user_id']) ||
                    !isset($arr['extras']))
                    continue;
                try{
                    JpushTool::push($arr['notice_title'],
                                    $arr['platform'],
                                    $arr['user_id'],
                                    $arr['extras']);
                    SQL::update(['table'  => 'push_timing_jobs',
                                 'where'  => ['job_id' => $re->job_id],
                                 'update' => ['send_state' => 1,
                                              'updated_at' => time()]]);
                    $success++;
                }catch(\Exception $e){
                    Log::info($e);
                }
            }
            Log::info('本次定时推送执行结果：应推送消息数-' . count($result) . ' , 实际成功-' . $success);
            Log::info('----------本次定时推送执行结束------------');
        }catch(\Exception $e){
            Log::info($e);
        }
    }

    /**
     * 工具
     */
    /**
     * 获取推送平台
     */
    static function get_platform($input){
        switch($input){
            case 0:
                return 0;
            case 1:
                return ['ios'];
            case 2:
                return ['android'];
        }
    }
}
